package com.etool.action.system;

import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import net.sf.json.JSONObject;

import com.etool.commons.utils.AjaxUtils;
import com.etool.modules.auth.model.NoRequireAuth;
import com.etool.modules.curd.service.CurdService;
import com.opensymphony.xwork2.ActionSupport;

public class MenuAction extends ActionSupport{
	private HttpServletRequest request=ServletActionContext.getRequest();
	private HttpServletResponse response=ServletActionContext.getResponse();
	private CurdService curdService;
	
	@Action(value="menu",results={@Result(name=SUCCESS,location="/system/menu-treegrid.jsp")})
	public String menu() throws IOException
	{	
		return SUCCESS;
	}
	
	@Action("menu-read")
	public String menuRead() throws IOException
	{
		List<Map<String, Object>> row=curdService.read("auth_menu", null, 0, 1000,"id");
		Map<String, Object> res=new HashMap<String, Object>();
		
		List<Map<String, Object>> rowTmp=new ArrayList<Map<String,Object>>();
		
		for(Map<String, Object> map:row)
		{
			int _parentId=(Integer)map.get("_parentId");
			if(_parentId==0)
			{
				Map<String, Object> tmp=new HashMap<String, Object>();
				
				tmp.putAll(map);
				tmp.remove("_parentId");
				rowTmp.add(tmp);
				continue;
			}
			rowTmp.add(map);
		}
		res.put("total", 10);
		res.put("rows", row);
		response.setContentType("text/html;charset=utf-8");
		response.getWriter().write(JSONObject.fromObject(res).toString());
		response.getWriter().flush();
		return NONE;
	}
	
	@Action("menu-id-up-1")
	public String menuUpdate()
	{
		try
		{
			int id=NumberUtils.toInt(request.getParameter("id"));
			int _parentId=NumberUtils.toInt(request.getParameter("_parentId"));
			
			String sql="update auth_menu set id=id+1 where id>=:id and _parentId=:_parentId";
			
			Map<String, Object> params=new HashMap<String, Object>();
			params.put("id", id);
			params.put("_parentId", _parentId);
			
			curdService.updateSql(sql,params);
			
			AjaxUtils.writeJson(response, Collections.singletonMap("success", (Object)true));
			return NONE;
		}
		catch(Exception e)
		{
			AjaxUtils.writeJson(response,Collections.singletonMap("errorMsg", (Object)e.getMessage()));
		}
		return NONE;
	}

	public CurdService getCurdService() {
		return curdService;
	}

	public void setCurdService(CurdService curdService) {
		this.curdService = curdService;
	}
}
